/**
 * 主JavaScript文件
 * 州弟医院信息系统 - 州弟学安全
 */

// 文档加载完成后执行
$(document).ready(function() {
    
    // 密码强度检测
    $('#password').on('keyup', function() {
        var password = $(this).val();
        var strength = checkPasswordStrength(password);
        
        $('.password-strength').removeClass('strength-weak strength-medium strength-strong');
        
        if (password.length > 0) {
            if (strength < 30) {
                $('.password-strength').addClass('strength-weak');
                $('.password-strength-text').text('弱');
            } else if (strength < 60) {
                $('.password-strength').addClass('strength-medium');
                $('.password-strength-text').text('中');
            } else {
                $('.password-strength').addClass('strength-strong');
                $('.password-strength-text').text('强');
            }
            $('.password-strength-container').show();
        } else {
            $('.password-strength-container').hide();
        }
    });
    
    // 密码确认验证
    $('#confirm_password').on('keyup', function() {
        if ($(this).val() === $('#password').val()) {
            $(this).removeClass('is-invalid').addClass('is-valid');
            $('.password-match-feedback').hide();
        } else {
            $(this).removeClass('is-valid').addClass('is-invalid');
            $('.password-match-feedback').show();
        }
    });
    
    // 表单验证
    $('.needs-validation').submit(function(event) {
        if (this.checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
        }
        $(this).addClass('was-validated');
    });
    
    // 科室选择联动医生列表
    $('#department').on('change', function() {
        var deptId = $(this).val();
        if (deptId) {
            $.ajax({
                url: 'get_doctors.php',
                type: 'POST',
                data: {department_id: deptId},
                dataType: 'json',
                success: function(response) {
                    var options = '<option value="">请选择医生</option>';
                    $.each(response, function(index, doctor) {
                        options += '<option value="' + doctor.id + '">' + doctor.name + ' - ' + doctor.position + '</option>';
                    });
                    $('#doctor').html(options).prop('disabled', false);
                }
            });
        } else {
            $('#doctor').html('<option value="">请先选择科室</option>').prop('disabled', true);
        }
    });
    
    // 日期选择器
    if ($.fn.datepicker) {
        $('.datepicker').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            language: 'zh-CN',
            todayHighlight: true
        });
    }
    
    // 时间选择器
    if ($.fn.timepicker) {
        $('.timepicker').timepicker({
            minuteStep: 15,
            showMeridian: false,
            defaultTime: '09:00'
        });
    }
    
    // 表格排序和搜索
    if ($.fn.DataTable) {
        $('.data-table').DataTable({
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.10.25/i18n/Chinese.json"
            }
        });
    }
    
    // 侧边栏切换
    $('.sidebar-toggle').on('click', function() {
        $('.admin-sidebar').toggleClass('show');
    });
    
    // 确认删除对话框
    $('.delete-confirm').on('click', function(e) {
        if (!confirm('确定要删除吗？此操作不可恢复！')) {
            e.preventDefault();
        }
    });
    
    // 图表初始化（如果页面有图表）
    initCharts();
});

// 密码强度计算函数
function checkPasswordStrength(password) {
    var strength = 0;
    
    // 长度检查
    if (password.length >= 8) {
        strength += 20;
    } else if (password.length >= 6) {
        strength += 10;
    }
    
    // 复杂度检查
    if (password.match(/[a-z]+/)) {
        strength += 10;
    }
    if (password.match(/[A-Z]+/)) {
        strength += 15;
    }
    if (password.match(/[0-9]+/)) {
        strength += 10;
    }
    if (password.match(/[^a-zA-Z0-9]+/)) {
        strength += 20;
    }
    
    // 重复字符检查
    if (password.match(/(.)\1{2,}/)) {
        strength -= 10;
    }
    
    return Math.max(strength, 0);
}

// 图表初始化函数
function initCharts() {
    if (typeof Chart !== 'undefined') {
        // 如果页面上有挂号量统计图表，初始化它
        var appointmentCtx = document.getElementById('appointmentChart');
        if (appointmentCtx) {
            var appointmentChart = new Chart(appointmentCtx, {
                type: 'line',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        label: '挂号量',
                        data: chartData.data,
                        backgroundColor: 'rgba(0, 123, 255, 0.2)',
                        borderColor: 'rgba(0, 123, 255, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // 科室统计饼图
        var departmentCtx = document.getElementById('departmentChart');
        if (departmentCtx) {
            var departmentChart = new Chart(departmentCtx, {
                type: 'pie',
                data: {
                    labels: deptChartData.labels,
                    datasets: [{
                        data: deptChartData.data,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.6)',
                            'rgba(54, 162, 235, 0.6)',
                            'rgba(255, 206, 86, 0.6)',
                            'rgba(75, 192, 192, 0.6)',
                            'rgba(153, 102, 255, 0.6)',
                            'rgba(255, 159, 64, 0.6)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'right',
                        }
                    }
                }
            });
        }
    }
}

// AJAX表单提交
function submitForm(formId, successCallback, errorCallback) {
    var form = $('#' + formId);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        success: function(response) {
            if (typeof successCallback === 'function') {
                successCallback(response);
            }
        },
        error: function(xhr, status, error) {
            if (typeof errorCallback === 'function') {
                errorCallback(xhr, status, error);
            } else {
                alert('提交失败: ' + error);
            }
        }
    });
    return false;
}

// 预览上传图片
function previewImage(input, previewId) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#' + previewId).attr('src', e.target.result).show();
        }
        reader.readAsDataURL(input.files[0]);
    }
} 